<?php
    include_once( PARAM_CLASS.'class.mysql.php' );
    class Tdatasource
    {
        var $table;     //  contains the name of table with added prefix `tbl_`
        var $fields;    //  : Field, Type, Null, Key, Default, Extra
        var $values;    //
        var $mysql;     // instance of Tmysql object

        function Tdatasource( $table, $db = '' ) //Constructor
        {
            $this->mysql = new Tmysql( $db );
            $this->table = PARAM_TABLE_PEFIX.$table;
            $this->get_fields();
        }

        function get_fields()// write to the $fields the structure of table
        {
            $this->mysql->sql_exe ( 'SHOW columns FROM  `'.$this->table.'`' );
            while ( $row = $this->mysql->fetch() )
            {
                $match = '';
                if(ereg('enum.(.*).', $row['Type'], $match))
                {
                    $opts = explode(',', $match[1]);
                    foreach ($opts as $item) $finalResult[] = substr($item, 1, strlen($item)-2);
                    $row['Enum'] = $finalResult;
                    $row['Type'] = 'enum';
                }
                if(ereg('.[a-z]{1,9}.(.[1-9]{1,9}).', $row['Type'], $match))
                {

                    $row['Lenth'] = $match[1];
                    ereg('.[a-z]{1,9}', $row['Type'], $match);
                    $row['Type'] = $match[0];
                }
                $this->fields[] = $row ;
                $row = array();
                $finalResult = array();
            };
        }

        function select( $value = ' 1 ', $fields = ' * ', $orderby = '' )
        {
            unset( $this->values );
            $this->values = array();
            if( empty( $value ) )  $value = ' 1 ';
            if( empty( $fields ) )  $fields = ' * ';
            $this->mysql->sql_query = 'SELECT '.$fields.' FROM `'.$this->table.'` WHERE '.$value .' ';
            if( !empty( $orderby ) )  { $this->mysql->sql_query .= ' ORDER BY '.$orderby.' '; };
            $this->mysql->sql_exe();
            if ( ! $this->mysql->num_rows ) { return false ; }
            else
            {
                $this->values = $this->mysql->fetch();
                if( is_array($this->values) ) foreach( $this->values as $k => $v ) { $this->values[$k] = stripslashes( $v );};
            };
            return( $this->mysql->num_rows );
        }


        function goto_id( $id, $fields = ' * ' )
        {
        //    echo $this->fields[i]['Field']; this will print the name of i column
            $this->mysql->sql_exe ( 'SELECT '.$fields.' FROM `'.$this->table.'` WHERE `'.$this->fields[0]['Field'].'` = "' . $id .'"' );
            if ( ! $this->mysql->num_rows ) { return false ; }
            else
            {
                $this->values = $this->mysql->fetch();
                if( is_array($this->values) ) foreach( $this->values as $k => $v ) { $this->values[$k] = stripslashes( $v ); };
            };
            return( $this->mysql->num_rows );
        }

        function next()
        {
            $this->values = $this->mysql->fetch();
            if( is_array($this->values) ) foreach( $this->values as $k => $v ) { $this->values[$k] = stripslashes( $v ); };
            return( $this->values );
        }



        function insert( $value = '' )
        {
            if( $value == '' ) { $value = $_REQUEST; };
            $this->mysql->sql_query = 'INSERT INTO `'.$this->table.'`( ';
            reset($this->fields);
            $i = 0;
            $val = '';
            $sqlsrt = '';
            $id = false;
            foreach( $this->fields as $k=>$v )
            {
                if( $k and isset( $value[$v['Field']] ) and ( $value[$v['Field']] ) and trim( $value[$v['Field']] ) and ( $v['Field'] != 'id' ) )
                {
                    if( $i )
                    {
                        $this->mysql->sql_query .= ' , ';
                        $val  .= ' , ';
                    }
                    else { $i = 1; };
                    $this->mysql->sql_query .= '`'.$v['Field'].'`';
                    $val .= '"'.$value[$v['Field']].'"';
                    $sqlsrt .= $v['Field']." => ".$value[$v['Field']]."\n";
                }
            }
            $this->mysql->sql_query .= ' ) VALUES ( '.$val.' ) ';
            $this->mysql->sql_exe();
            $id = mysql_insert_id( $this->mysql->conn_id );

            $this->mysql->sql_exe( ' INSERT INTO `'.PARAM_TABLE_PEFIX.'log`(    `user`,
                                                                                `date`,
                                                                                `tblname`,
                                                                                `sqlid`,
                                                                                `action`,
                                                                                `sqlstr` )
                                     VALUES(                                    '.(isset($_SESSION['userInfo']['id'])?$_SESSION['userInfo']['id']:1).',
                                                                                "'.date('Y-m-d h:i:s').'",
                                                                                "'.$this->table.'",
                                                                                '.mysql_insert_id( $this->mysql->conn_id ).',
                                                                                "insert",
                                                                                "'.addslashes($sqlsrt).'" )' );

            return $id;
        }

        function delete( $id )
        {
            if ( $this->del_possible( $id ) )
            {
                $oldval = '';
                $this->mysql->sql_exe ( 'SELECT * FROM `'.$this->table.'` WHERE `'.$this->fields[0]['Field'].'` = "'. $id .'"' );
                $row = $this->mysql->fetch();
                foreach( $this->fields as $k=>$v )
                {
                    $oldval .= $v['Field']." => ".$row[$v['Field']]."\n";
                }
                $this->mysql->sql_exe ( 'DELETE FROM `'.$this->table.'` WHERE `'.$this->fields[0]['Field'].'` = "'. $id .'"' );
                $this->mysql->sql_exe( ' INSERT INTO `'.PARAM_TABLE_PEFIX.'log`(    `user`,
                                                                                    `date`,
                                                                                    `tblname`,
                                                                                    `sqlid`,
                                                                                    `action`,
                                                                                    `oldvalues` )
                                         VALUES(                                    '.(isset($_SESSION['userInfo']['id'])?$_SESSION['userInfo']['id']:1).',
                                                                                    "'.date('Y-m-d h:i:s').'",
                                                                                    "'.$this->table.'",
                                                                                    '.$id.',
                                                                                    "delete",
                                                                                    "'.addslashes($oldval).'" )' );
            }
        }

        function update( $id, $value = '' )
        {
            if( $value == '' ) { $value = $_REQUEST; };

            $oldval = '';
            $this->mysql->sql_exe ( 'SELECT * FROM `'.$this->table.'` WHERE `'.$this->fields[0]['Field'].'` = "'. $id .'"' );
            $row = $this->mysql->fetch();

            $this->mysql->sql_query = 'UPDATE `'.$this->table.'` SET ';
            reset($this->fields);
            $i = 0;
            $sqlsrt = '';
            foreach( $this->fields as $k=>$v )
            {
                if( $k and isset( $value[$v['Field']] )   )
                {
                    if( $i ) { $this->mysql->sql_query .= ' , '; }
                    else { $i++; };
                    $this->mysql->sql_query .= '`'.$v['Field'].'` = "'.$value[$v['Field']].'" ';
                }
                if( isset( $value[$v['Field']] ) and ( $value[$v['Field']] != $row[$v['Field']] ) )
                {
                    $sqlsrt .= $v['Field']." => ".$value[$v['Field']]."\n";
                    $oldval .= $v['Field']." => ".$row[$v['Field']]."\n";
                }
            }
            $this->mysql->sql_query .= ' WHERE `'.$this->fields[0]['Field'].'` = "' . $id .'"';
            $this->mysql->sql_exe();

            $this->mysql->sql_exe( ' INSERT INTO `'.PARAM_TABLE_PEFIX.'log`(    `user`,
                                                                                `date`,
                                                                                `tblname`,
                                                                                `sqlid`,
                                                                                `action`,
                                                                                `sqlstr`,
                                                                                `oldvalues` )
                                     VALUES(                                    '.(isset($_SESSION['userInfo']['id'])?$_SESSION['userInfo']['id']:1).',
                                                                                "'.date('Y-m-d h:i:s').'",
                                                                                "'.$this->table.'",
                                                                                '.$id.',
                                                                                "update",
                                                                                "'.addslashes($sqlsrt).'",
                                                                                "'.addslashes($oldval).'" )' );
        }
         function del_possible( $id ) { return true; }
    }
?>